package com.gitee.feizns.quickstart.upload;

import com.gitee.feizns.dynamic.io.Ios;
import lombok.SneakyThrows;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.channels.Channels;

/**
 * 磁盘文件存储
 * @author feizns
 * @since 2025/2/12
 */
public class DiskFileStorage implements FileStorage {

    /**
     * 存储目录
     */
    private final File directory;

    /**
     * 本地文件系统存储
     * @param directory 目录
     */
    public DiskFileStorage(String directory) {
        this.directory = new File(directory);
        if ( !this.directory.exists() && !this.directory.mkdirs() )
            throw new IllegalArgumentException("目录创建失败：" + this.directory);
        if ( !this.directory.isDirectory() )
            throw new IllegalArgumentException("非法目录文件路径：" + this.directory);
    }

    @SneakyThrows
    @Override
    public void put(String key, InputStream is) {
        File file = new File(directory, key);
        ifNotExistsMkDirs(file);
        try( FileOutputStream fos = new FileOutputStream(file) ) {
            fos.getChannel().transferFrom(Channels.newChannel(is), 0, Long.MAX_VALUE);
//            Ios.write(is, fos);
        }
    }

    @SneakyThrows
    @Override
    public InputStream get(String key) {
        try (FileInputStream fis = new FileInputStream(new File(directory, key))) {
            return Ios.clone(Channels.newInputStream(fis.getChannel()), 1)[0];
//            return Ios.clone(fis, 1)[0];
        }
    }

    @Override
    public boolean exist(String key) {
        return new File(directory, key).exists();
    }

    @Override
    public boolean delete(String key) {
        return new File(directory, key).delete();
    }

    /**
     * 如果不存在目录则创建
     */
    private void ifNotExistsMkDirs(File file) {
        File parent = file.getParentFile();
        if ( !parent.exists() && !parent.mkdirs() )
            throw new IllegalArgumentException("目录创建失败：" + parent);
    }

}
